package com.itany.book.interceptor;

import com.itany.book.ApplicationContextHold;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Author:yaozhiyuan0117@163.com
 * Time:2019/12/29 17:19
 * Describe:
 * version:1.0
 */
public class MyInterceptor implements HandlerInterceptor {

    // 因为MyInterceptor类后面new出来加入register中的，无法进行@autowired
    // @Autowired
    // private StringRedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 通过ApplicationContextHold继承ApplicationContextAware
        // 进行提升，获得可以得到ac容器，从而获得里面的内容！
        StringRedisTemplate redisTemplate = ApplicationContextHold.getBean(StringRedisTemplate.class);
        boolean flag = false;
        Cookie[] cks = request.getCookies();
        if(null!=cks){
            for(int i=0;i<cks.length;i++){
                Cookie ck = cks[i];
                if("TT_TOKEN".equals(ck.getName())){
                    String token = ck.getValue();
                    String str =redisTemplate.opsForValue().get("USER_TOKEN::"+token);
                    System.out.println("====================="+str);
                    flag=true;
                }
            }
        }
        return flag;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {

    }
}
